<?php

namespace App\Http\Controllers\Admin;

use App\Services\WxMaterial\WxMaterialService;
use Illuminate\Http\Request;
/**
 * 微信素材分类管理
 * @package App\Http\Controllers\Admin
 */
class WxMaterialCategoryController extends BaseWxController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 菜单管理首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request, WxMaterialService $wxMaterialSer)
    {
        if ($request->ajax()){
            $materialType = $request->get('material_type', 0);
            $catList = $wxMaterialSer->getCatList($materialType);
            foreach ($catList as $k => $v){
                $v['text'] = $v['name'];
                $v['tags'] = ['排序：'.$v['order_num']];
                $catList[$k] = $v;
            }

            //树结构菜单列表
            $tree = new \App\Services\Tool\TreeService('cat_id', 'parent_id', 'nodes');
            $tree->load($catList);
            $treeCatList = $tree->deepTree();
            $data['catList'] = $treeCatList ? $treeCatList : [];
            return $data;
        }
        //全部分组数据
        $this->viewData['materialType'] = $wxMaterialSer->getMaterialTypeList();

        return view('admin.wxmaterialcategory.index', $this->viewData);
    }

    /**
     * 保存、添加菜单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function save(\App\Http\Requests\AdminWxMaterialCategoryPost $request, WxMaterialService $wxMaterialSer)
    {
        try {
            $rs = $wxMaterialSer->saveCat($request);
            if ($rs) {
                return $this->showMsg('success', ($request->input('menu_id') ? '编辑' : '添加') . '成功', [], 'admin.wxmaterialcategory.index');
            }
            throw new \Exception(($request->input('menu_id') ? '编辑' : '添加') . '菜单失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 删除菜单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function destroy(Request $request, WxMaterialService $wxMaterialSer)
    {
        try {
            $id = $request->input('cat_id', 0);
            if (!$id) {
                throw new \Exception('请指定要删除的菜单');
            }
            $rs = $wxMaterialSer->delCat($id);
            if (!$rs) {
                throw new \Exception('删除失败');
            }
            return $this->showMsg('success', '删除成功');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }
}
